/*******************************************************************************
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package edu.columbia.sportsleagueandroid.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.TextAreaElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import edu.columbia.sportsleagueandroid.client.MyRequestFactory.HelloWorldRequest;
import edu.columbia.sportsleagueandroid.client.MyRequestFactory.MessageRequest;
import edu.columbia.sportsleagueandroid.shared.MessageProxy;
import edu.columbia.sportsleagueandroid.shared.SportsLeagueAndroidRequest;
import edu.columbia.sportsleagueandroid.shared.StadiumProxy;

public class SportsLeagueAndroidWidget extends Composite 
{

  public boolean tempResult = false;
  public String finalResponse;
  
  private static final int STATUS_DELAY = 4000;
  private static final String STATUS_ERROR = "status error";
  private static final String STATUS_NONE = "status none";
  private static final String STATUS_SUCCESS = "status success";

  interface SportsLeagueAndroidUiBinder extends UiBinder<Widget, SportsLeagueAndroidWidget> {
  }

  private static SportsLeagueAndroidUiBinder uiBinder = GWT.create(SportsLeagueAndroidUiBinder.class);

  @UiField
  TextAreaElement messageArea;
  
  @UiField
  Button show;
  
  
  @UiField
  TextAreaElement runs;
  
  @UiField
  TextAreaElement recipientArea;

  @UiField
  DivElement status;

  @UiField
  Button sayHelloButton;

  @UiField
  Button sendMessageButton;


  /**
   * Timer to clear the UI.
   */
  Timer timer = new Timer() 
  {
    @Override
    public void run() 
    {
      status.setInnerText("");
      status.setClassName(STATUS_NONE);
      recipientArea.setValue("");
      messageArea.setValue("");
    }
  };

  private void setStatus(String message, boolean error) 
  {
    status.setInnerText(message);
    if (error) 
    {
      status.setClassName(STATUS_ERROR);
    } 
    else 
    {
      if (message.length() == 0) 
      {
        status.setClassName(STATUS_NONE);
      } 
      else 
      {
        status.setClassName(STATUS_SUCCESS);
      }
    }

    timer.schedule(STATUS_DELAY);
  }

  public SportsLeagueAndroidWidget() 
  {
    initWidget(uiBinder.createAndBindUi(this));
    sayHelloButton.getElement().setClassName("send centerbtn");
    sendMessageButton.getElement().setClassName("send");

    final EventBus eventBus = new SimpleEventBus();
    final MyRequestFactory requestFactory = GWT.create(MyRequestFactory.class);
    requestFactory.initialize(eventBus);
    
    
    show.addClickHandler(new ClickHandler() 
    {
    public void onClick(ClickEvent event) 
    {
        //String recipient = recipientArea.getValue();
        //String receivers[] = recipient.split(",");
        String message = messageArea.getValue();
       // setStatus("Connecting...", false);
        sendMessageButton.setEnabled(false);
        sendNewTaskToServer(message);
    }
    private void sendNewTaskToServer(String message) {
        SportsLeagueAndroidRequest request = requestFactory.sportsLeagueAndroidRequest();
        StadiumProxy task = request.create(StadiumProxy.class);
       // int len = Math.min(message.length(), 50);
     String stad [] = message.split(",");
        task.setStadiumCapacity(Long.parseLong(stad[3]));
        task.setStadiumCity(stad[1]);
        task.setStadiumCountry(stad[2]);
        task.setStadiumName(stad[0]);
        //setStatus("Connecting", false);
        setStatus(task.toString(), false);
        request.updateStadium(task).fire();
        //tasksList.add(task);
        
      }
    
    });
      
    
    sendMessageButton.addClickHandler(new ClickHandler() 
    {
    public void onClick(ClickEvent event) 
    {
        String recipient = recipientArea.getValue();
        String receivers[] = recipient.split(",");
        String message = messageArea.getValue();
        setStatus("Connecting...", false);
        sendMessageButton.setEnabled(false);

        
        Request<String> sendRequest = null;
         // Send a message using RequestFactory
        for(int count=0;count<receivers.length;count++)
        {
            MessageRequest request = requestFactory.messageRequest();
	        MessageProxy messageProxy = request.create(MessageProxy.class);
	        messageProxy.setRecipient(receivers[count]);
	        messageProxy.setMessage(message);
	        sendRequest = request.send().using(messageProxy);
	        
	        sendRequest.fire(new Receiver<String>() 
	        {
	          @Override
	          public void onFailure(ServerFailure error) 
	          {
	        	tempResult |= false;
	        	finalResponse = error.getMessage();
	            setStatus(error.getMessage(), !tempResult);
	          }
	
	          @Override
	          public void onSuccess(String response) 
	          {
	        	tempResult |= true;
	        	finalResponse = response;
	          }
	          
	        });
	    } 
        
        sendMessageButton.setEnabled(true);
        if(tempResult)
        {
        	setStatus(finalResponse, finalResponse.startsWith("Failure:"));
        }
        else
        {
        	setStatus(finalResponse, !tempResult);
        }
      }
    });
    
    sayHelloButton.addClickHandler(new ClickHandler() 
    {
      public void onClick(ClickEvent event) 
      {
        sayHelloButton.setEnabled(false);
        HelloWorldRequest helloWorldRequest = requestFactory.helloWorldRequest();
        helloWorldRequest.getMessage().fire(new Receiver<String>() 
        {
          @Override
          public void onFailure(ServerFailure error)
          {
            sayHelloButton.setEnabled(true);
            setStatus(error.getMessage(), true);
          }

          @Override
          public void onSuccess(String response) 
          {
            sayHelloButton.setEnabled(true);
            setStatus(response, response.startsWith("Failure:"));
          }
        });
      }
    });
  }
    
  
}

